<template>
  <n-card :bordered="false">
    <div>
      <basic-form
        :schemas='schemas'
        :labelWidth='labelWidth'
        :gridProps='gridProps'
        @handleSearch='handleSearch'
        :pageParams='pageParams'
        size='small'
        ref="userSearchRef"
      >
      </basic-form>
      
      <basic-table
        :title='title'
        :data='data'
        :columns='columns'
        :loading="loading"
      >
        <template #tableTitle>
          <n-space>
            <n-button type='info' @click='handleAdd()'>添加</n-button>
          </n-space>
        </template>      
      </basic-table>

      <!-- 
        分页。
        为什么不用data-table自带的pagination分页呢？
        因为我发现table的pagination传递itemCount总条数时不生效，
        等找到解决方法时将pagination对象传递给basic-form即可
      -->
      <div class="pagination mt10">
        <n-pagination
          :item-count='pageConfig.total'
          :page-sizes='pageConfig.pageSizes'
          :showSizePicker='pageConfig.showSizePicker'
          :show-quick-jumper='pageConfig.showQuickJumper'
          :on-update:page="(pageNum)=>changePagination('pageNum', pageNum)"
          :on-update:page-size="(pageSize) => changePagination('pageSize', pageSize)"
          />
      </div>
    </div>

    <n-modal
      v-model:show='showModal'
      :show-icon="false"
      style="width:650px"
      :title="modalTitle"
      preset="dialog">
      <n-form :model='form' ref='formRef'>
        <n-grid :cols="24" :x-gap="24">
          <n-form-item-gi :span="12" label="用户登录名" path="username">
            <n-input v-model:value="form.username" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='用户名称' path='nickname'>
            <n-input v-model:value="form.nickname" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="手机号" path="phone">
            <n-input v-model:value="form.phone" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='邮箱' path='email'>
            <n-input v-model:value="form.email" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="性别" path="gender">
            <n-radio-group v-model:value="form.gender" name="gender">
              <n-space>
                <n-radio
                  v-for='item in genderOption'
                  :key='item.dictValue'
                  :value='item.dictValue'
                  :label='item.dictValue'>{{ item.dictLabel }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='状态' path='status'>
            <n-radio-group v-model:value="form.status" name="status">
              <n-space>
                <n-radio
                  v-for='item in statusOption'
                  :key='item.dictValue'
                  :value='item.dictValue'
                  :label='item.dictValue'>{{ item.dictLabel }}</n-radio>
              </n-space>
            </n-radio-group>
          </n-form-item-gi>
          <n-form-item-gi :span="12" label="角色" path="roleIds">
            <n-input v-model:value="form.roleIds" placeholder="请输入名称" />
          </n-form-item-gi>
          <n-form-item-gi :span="12" label='备注' path='remark'>
            <n-input v-model:value="form.remark" type="textarea" :autosize="{ minRows: 3 }" placeholder="请输入备注信息" />
          </n-form-item-gi>
        </n-grid>
      </n-form>

      <template #action>
        <n-space>
          <n-button @click='() => (showModal=false)'>取消</n-button>
          <n-button @click='submitForm' :loading='btnLoading' type="info">确定</n-button>
        </n-space>
      </template>
    </n-modal>
  </n-card>
</template>

<script lang="ts" setup>
  import { onMounted, ref, unref, reactive, getCurrentInstance, computed, h } from 'vue'
  import { BasicTable } from '@/components/Table'
  import { BasicForm } from '@/components/Form'
  import { list, del } from '@/api/commonApi'
  import { OrderType } from '@/enums/tableEnum'
  import { addUser, updateUser } from '@/api/system/user'
  import { ResponseCode } from '@/enums/httpEnum'
  import { useStore } from 'vuex'
  import OperateButton from '@/components/OperateButton/index.vue'

  const internalInstance = getCurrentInstance()
  const store = useStore()
  const userSearchRef = ref()
  const formRef = ref()
  const data = ref([])
  const genderOption = computed(() => store.getters.genderOption)
  const statusOption = computed(() => store.getters.statusOption)

  const { selectDictLabel, $dialog, $notification, $message } = internalInstance?.appContext.config.globalProperties

  /** 分页查询参数 */
  const pageParams = reactive({
    orderByColumn: 'create_time',
    isAsc: OrderType.DESC,
    pageNum: 1,
    pageSize: 10
  })

  /** 分页配置 */
  const pageConfig = reactive({
    total: 0,
    pageSizes: [10, 20, 30, 40],
    showSizePicker: true,
    showQuickJumper: true
  })

  /** 点击分页上的按钮 */
  function changePagination(name: string, value: number) {
    pageParams[name] = value
    userSearchRef.value.handleSubmit()
  }

  /** 查询条件label宽度 */
  const labelWidth = 110
  /** 查询条件表单布局 */
  const gridProps = { cols: '1 500:2 800:3 1000:4 1250:5 1500:6' }
  /** 查询条件字段组件 */
  const schemas = [
    {
      field: 'username',
      component: 'NInput',
      label: '用户名',
      placeholder: '请输入用户名',
      giProps: {
        span: 1
      }
    }, {
      field: 'nickname',
      component: 'NInput',
      label: '昵称',
      placeholder: '请输入昵称'
    }, {
      field: 'phone',
      component: 'NInput',
      label: '手机号',
      placeholder: '请输入手机号'
    }, {
      field: 'status',
      component: 'NRadio',
      label: '状态',
      componentProps: {
        options: [...statusOption.value]
      }
    }, {
      field: 'birthday_start',
      component: 'NDatePicker',
      label: '创建日期开始',
      componentProps: {
        placeholder: '请选择开始创建日期',
      }
    }, {
      field: 'birthday_end',
      component: 'NDatePicker',
      label: '创建日期结束',
      componentProps: {
        placeholder: '请选择结束创建日期'
      }
    }
  ]

  /** 查询条件表单提交 */
  function handleSearch(params: any) {
    getUserList(params)
  }
  
  /** table标题 */
  const title = ref('用户管理')
  /** table字段 */
  const columns = ref([
    {
      title: '用户名',
      key: 'username',
      width: 120
    }, {
      title: '用户昵称',
      key: 'nickname',
      width: 120
    }, {
      title: '手机号',
      key: 'phone',
      width: 165
    }, {
      title: '邮箱',
      key: 'email',
      width: 120
    }, {
      title: '性别',
      key: 'gender',
      width: 60,
      align: 'center',
      render(row: any) {
        return selectDictLabel(genderOption.value, row.gender)
      }
    }, {
      title: '状态',
      key: 'status',
      width: 60,
      align: 'center',
      render(row: any) {
        return selectDictLabel(statusOption.value, row.status)
      }
    }, {
      title: '创建日期',
      key: 'createTime',
      width: 230,
      align: 'center',
    }, {
      title: '备注',
      key: 'remark',
      width: 150
    }, {
      title: '操作',
      key: 'operate',
      width: 160,
      align: 'center',
      render: function(row: any) {
        return h(OperateButton, {
          buttonList: [
            { title: '编辑', type: 'info', size: 'small', onClick: () => handleEdit(row) },
            { title: '删除', type: 'error', size: 'small', onClick: () => handleDelete(row) }
          ]
        })
      }
    }
  ])
  /** table是否loading */
  const loading = ref(false)

  const baseUrl = '/system/user'

  /** 获取用户列表 */
  function getUserList(params: any) {
    loading.value = true
    // const result = await list(baseUrl, { ...params, ...pageParams })
    // console.log('result', result)
    list(baseUrl, { ...params, ...pageParams }).then((result: any) => {
      data.value = result.data
      pageConfig.total = result.total
    }).finally(() => {
      loading.value = false
    })
  }

  /** 新增时，表单的默认值 */
  const defaultForm = {
    status: '1'
  }
  /** 新增、编辑表单 */
  const form = ref({} as any)
  /** 表单标题 */
  const modalTitle = ref('添加用户')
  /** modal是否显示 */
  const showModal = ref(false)
  /** modal的提交按钮loading */
  const btnLoading = ref(false)

  /** 提交新增、编辑表单 */
  async function submitForm() {
    btnLoading.value = true
    const id = unref(form).id

    if(id) {
      await updateUser(unref(form))
      $message.success('修改成功')
    } else {
      await addUser(unref(form))
      $message.success('添加成功')
    }
    showModal.value = false
    userSearchRef.value.handleSubmit()
    btnLoading.value = false
  }

  /** “添加”按钮 */
  function handleAdd() {
    modalTitle.value = '添加用户'
    showModal.value = true
    form.value = defaultForm
  }

  /** “编辑”按钮 */
  function handleEdit(row: any) {
    modalTitle.value = '编辑用户'
    showModal.value = true
    form.value = { ...row }
  }

  /** 删除按钮 */
  function handleDelete(row: any) {
    const id = row.id
    
    $dialog.error({
      title: '提示',
      content: `确定要删除【${row.username}】吗`,
      positiveText: '确定',
      negativeText: '取消',
      onPositiveClick: () => {
        del(baseUrl, id).then(() => {
          data.value = data.value.filter((item: any) => !id.includes(item.id))
          $notification.success({
            content: '删除成功',
            duration: 1500
          })
        })
      },
      onNegativeClick: () => {}
    })
    
  }
  
  onMounted(() => {
    // 调用查询表单的查询方法
    userSearchRef.value.handleSubmit()
  })

</script>

<style lang='stylus' scoped>
  .pagination
    display flex
    justify-content end
</style>